package iterator;
import global.*;
import heap.*;

public class PositionScan implements GlobalConst {
	private String filename ;
	private int[] allAttrs;
	public PositionScan(String cfilename, int[] Attrs)
	{
		filename = cfilename;
		allAttrs = Attrs;
	}

	public Tuple returnTuple(int position)
	{
			Tuple Tfinal = new Tuple();
		  AttrType [] Stypes = new AttrType[1]; //one attribute
	  	  //String metafilename = "filename" + ".hdr" ; // reading meta data file
	  	  try{
	  		  //FileDetails fd = new FileDetails(metafilename);
	  		  //FileDetails fd = new FileDetails();
	  		  int _totcols = 4;
	  		  
	  		  AttrType [] fd = new AttrType[4];
	  		  fd[0] = new AttrType(AttrType.attrString);
	  		  fd[1] = new AttrType(AttrType.attrString);
	  		  fd[2] = new AttrType(AttrType.attrInteger);
	  		  fd[3] = new AttrType(AttrType.attrInteger);
	  		  
	  			short[] fdsize = new short[2];
	  		  fdsize[0] = 32 ;
	  		  fdsize[1] = 32 ;
	  		  //Tfinal.setHdr(fd._totcols, fd._attrTyp, fd._attrSize);
	  		  Tfinal.setHdr((short)_totcols, fd, fdsize);
	  		  String[] coldata = new String[_totcols];
	  	      RID rtemp = new RID();
	  	      // open each column file for scan
	  	      for (int i = 0; i <_totcols; i++)
	  	      { 
	  	    	  short [] Ssizes = new short [1];
	  	    	  Heapfile hcol = new Heapfile(filename+i);
	  			  Tuple tcol = new Tuple(); 
	  			  switch(i)
	  			  {
	  			  case 0 :
	  				  Stypes[0] = new AttrType(AttrType.attrString); 
	  				  Ssizes[0] = strlen ; break ;
	  			  case 1 :
	  				  Stypes[0] = new AttrType(AttrType.attrString); 
	  				  Ssizes[0] = strlen ; break ;
	  			  case 2 :
	  				  Stypes[0] = new AttrType(AttrType.attrInteger);break ;
	  			  case 3 :
	  				  Stypes[0] = new AttrType(AttrType.attrInteger);break ;
	  		      default :
	  					  Stypes[0] = new AttrType(AttrType.attrString);  break ;
	  			  }		  
	  			  int pos = position ;
	  			  boolean status;
	  			  status = hcol._findPositionPage(rtemp, pos);
	  			
	  			  Tuple tcolumn = new Tuple();
	  			  tcolumn.setHdr((short)1, Stypes, Ssizes);
	  			  Tuple tcolumn2 = new Tuple(tcolumn.size());
	  			  
	  	     	  tcolumn2 = hcol.getRecord(rtemp);
	  	     	  tcolumn.tupleCopy(tcolumn2) ;
	  	     	  
	  	     	 if (fd[i].attrType==0)
	  	     	 {
	  	     	   coldata[i] = tcolumn.getStrFld(1);
	  	     	 }
	  	     	 else
	  	     	 {
	  	     	   coldata[i] = Integer.toString(tcolumn.getIntFld(1));
	  	     	 }
	  	     	  
	  	      }	    
	  		
	  	    Tuple Tfin = new Tuple(Tfinal.size());
	  	    Tfin.setHdr((short)_totcols, fd, fdsize);
	  	    for(int y=0;y<(int)_totcols;y++)
	  		 {
	  			 if(fd[y].attrType==0)
	  				 Tfin.setStrFld(y+1,coldata[y].trim());
	  			 else
	  				 Tfin.setIntFld(y+1,Integer.parseInt(coldata[y].trim()));
	  		 }
	  	    Tfinal.tupleCopy(Tfin);
	  	  
	  	 }
	  	 catch (Exception e)
	  	 {
	  		 System.out.println("Error" + e.toString());
	  	} 	
			
		return Tfinal;
	}

}